from flask import Blueprint, jsonify, request
import os
from .validators import validate_create_task_params
from ai_tasks import task_manager  # 直接从根目录导入
from .database import get_all_tasks, get_task_from_db
import logging
import traceback

# 配置日志
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

# 创建蓝图
api_bp = Blueprint('api', __name__)

@api_bp.route('/')
def api_home():
    """API首页"""
    return jsonify({
        "message": "Flask API 服务运行中",
        "version": "1.0.0",
        "endpoints": {
            "health": "/api/health",
            "info": "/api/info",
            "echo": "/api/echo",
            "createtask": "/api/createtask",
            "tasks": "/api/tasks",
            "task_status": "/api/task/<task_id>",
            "task_status_new": "/api/tasks/<task_id>/status",
            "task_result": "/api/task/<task_id>/result"
        }
    })

@api_bp.route('/health')
def health():
    """健康检查接口"""
    return jsonify({
        "status": "healthy",
        "service": "flask-api"
    })

@api_bp.route('/info', methods=['GET'])
def get_info():
    return jsonify({
        "message": "API is running",
        "version": "1.0.0",
        "status": "healthy",
        "report_agent_available": task_manager.report_workflow is not None
    })

@api_bp.route('/echo', methods=['POST'])
def echo():
    """回声接口"""
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({"error": "请提供JSON数据"}), 400
        
        return jsonify({
            "message": "数据接收成功",
            "received_data": data,
            "method": request.method
        })
    
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@api_bp.route('/createtask', methods=['POST'])
def create_task():
    """创建文章生成任务"""
    try:
        data = request.get_json()
        if not data:
            return jsonify({
                'success': False,
                'error': '无效的请求数据'
            }), 400
            
        # 检查必需字段
        if not data.get('requirement'):
            return jsonify({
                'success': False,
                'error': '需求描述不能为空'
            }), 400
            
        # 创建任务
        task = task_manager.create_task(
            requirement=data.get('requirement'),
            task_type=data.get('task_type', 'report_generation'),
            priority=data.get('priority', 'normal')
        )
        
        return jsonify({
            'success': True,
            'data': {
                'id': task['id'],
                'status': task['status'],
                'created_at': task['created_at'].isoformat()
            }
        })
        
    except Exception as e:
        logger.error(f"创建任务失败: {str(e)}")
        logger.error(traceback.format_exc())
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@api_bp.route('/tasks', methods=['GET'])
def get_tasks():
    """获取所有任务"""
    try:
        tasks = get_all_tasks()
        return jsonify({
            "success": True,
            "tasks": tasks,
            "total": len(tasks)
        })
    
    except Exception as e:
        return jsonify({
            "success": False,
            "error": f"获取任务列表失败: {str(e)}"
        }), 500

@api_bp.route('/api/tasks/<task_id>/status', methods=['GET'])
def get_task_status(task_id):
    """获取任务状态"""
    try:
        logger.info(f"查询任务状态: {task_id}")
        
        # 从数据库获取任务信息
        task = get_task_from_db(task_id)
        if not task:
            return jsonify({
                'success': False,
                'error': '任务不存在'
            }), 404
        
        # 从任务管理器获取详细状态
        task_manager_instance = get_task_manager()
        detailed_status = task_manager_instance.get_task_status(task_id)
        
        # 构建返回数据
        result = {
            'success': True,
            'task_id': task_id,
            'status': task['status'],
            'progress': task.get('progress', 0),
            'created_at': task['created_at'],
            'updated_at': task['updated_at'],
            'agent_status': detailed_status.get('agent_status', {}),
            'logs': detailed_status.get('logs', []),
            'errors': detailed_status.get('errors', [])
        }
        
        # 如果有优化后的prompt，添加到返回数据中
        if 'optimized_prompt' in detailed_status:
            result['optimized_prompt'] = detailed_status['optimized_prompt']
        
        # 如果有计划数据，添加到返回数据中  
        if 'plan' in detailed_status:
            result['plan'] = detailed_status['plan']
            
        # 如果有内容，添加到返回数据中
        if 'content' in detailed_status:
            result['content'] = detailed_status['content']
            
        # 如果有质量评分，添加到返回数据中
        if 'quality_score' in detailed_status:
            result['quality_score'] = detailed_status['quality_score']
        
        logger.info(f"返回任务状态: {result}")
        return jsonify(result)
        
    except Exception as e:
        logger.error(f"获取任务状态失败: {str(e)}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

def get_task_result(task_id):
    """获取任务完整结果的辅助函数"""
    try:
        # 首先从内存中的task_manager查找
        if task_id in task_manager.tasks:
            task = task_manager.tasks[task_id]
            return {
                "success": True,
                "task_id": task_id,
                "status": task['status'],
                "result": task.get('result'),
                "error": task.get('error'),
                "created_at": task['created_at'].isoformat(),
                "task_type": task.get('task_type', 'unknown'),
                "priority": task.get('priority', 'normal')
            }
        
        # 如果内存中没有，尝试从数据库查找
        task_data = get_task_from_db(task_id)
        if task_data:
            return {
                "success": True,
                "task_id": task_id,
                "status": task_data['status'],
                "created_at": task_data['created_at'],
                "updated_at": task_data['updated_at'],
                "keyword": task_data.get('keyword'),
                "category": task_data.get('category'),
                "article_count": task_data.get('article_count'),
                "priority": task_data['priority'],
                "progress": task_data.get('progress', {}),
                "articles": task_data.get('articles', [])
            }
        
        # 任务不存在
        return {
            "success": False,
            "error": f"任务 {task_id} 不存在"
        }
        
    except Exception as e:
        logger.error(f"获取任务结果失败: {str(e)}")
        return {
            "success": False,
            "error": f"获取任务结果失败: {str(e)}"
        }

def test_report_agent():
    """测试reportAgent功能的辅助函数"""
    try:
        # 检查reportAgent是否可用
        if task_manager.report_workflow is None:
            return {
                "success": False,
                "error": "reportAgent未初始化"
            }
        
        return {
            "success": True,
            "message": "reportAgent可用",
            "workflow_status": "initialized"
        }
    except Exception as e:
        logger.error(f"测试reportAgent失败: {str(e)}")
        return {
            "success": False,
            "error": f"测试失败: {str(e)}"
        }

# 路由定义
@api_bp.route('/task/<task_id>', methods=['GET'])
def get_task(task_id):
    """获取特定任务状态"""
    try:
        logger.info(f"查询任务状态，ID: {task_id}")
        
        # 获取任务状态
        status_result = get_task_status(task_id)
        
        if not status_result["success"]:
            return jsonify(status_result), 404
        
        return jsonify(status_result)
    
    except Exception as e:
        logger.error(f"查询任务时发生错误: {str(e)}")
        logger.error(f"错误详情: {traceback.format_exc()}")
        return jsonify({
            "success": False,
            "error": f"查询任务失败: {str(e)}"
        }), 500

@api_bp.route('/task/<task_id>/result', methods=['GET'])
def get_task_result_api(task_id):
    """获取任务完整结果"""
    try:
        logger.info(f"获取任务结果，ID: {task_id}")
        
        result = get_task_result(task_id)
        
        if not result["success"]:
            return jsonify(result), 404
        
        return jsonify(result)
        
    except Exception as e:
        logger.error(f"获取任务结果时发生错误: {str(e)}")
        return jsonify({
            "success": False,
            "error": f"获取任务结果失败: {str(e)}"
        }), 500

@api_bp.route('/test/reportagent', methods=['GET'])
def test_reportagent():
    """测试 reportAgent 功能"""
    try:
        logger.info("开始测试 reportAgent")
        
        result = test_report_agent()
        
        return jsonify(result)
        
    except Exception as e:
        logger.error(f"测试 reportAgent 时发生错误: {str(e)}")
        return jsonify({
            "success": False,
            "error": f"测试失败: {str(e)}"
        }), 500

@api_bp.route('/debug/agent-status', methods=['GET'])
def debug_agent_status():
    """调试：检查 reportAgent 状态"""
    try:
        # 检查环境变量
        openai_key = os.getenv('OPENAI_API_KEY')
        
        # 检查文件路径
        current_dir = os.path.dirname(os.path.abspath(__file__))
        project_root = os.path.dirname(current_dir)
        agent_path = os.path.join(project_root, 'agent', 'reportAgent')
        
        # 检查必要文件
        required_files = [
            'simple_workflow.py',
            'base_agent.py', 
            'state.py',
            'config.py',
            'utils.py'
        ]
        
        file_status = {}
        for file_name in required_files:
            file_path = os.path.join(agent_path, file_name)
            file_status[file_name] = os.path.exists(file_path)
        
        # 尝试重新初始化（如果方法存在）
        reinit_success = False
        try:
            if hasattr(task_manager, 'reinit_report_agent'):
                reinit_success = task_manager.reinit_report_agent()
        except Exception as e:
            logger.warning(f"重新初始化失败: {str(e)}")
        
        return jsonify({
            "success": True,
            "debug_info": {
                "openai_key_set": openai_key is not None,
                "openai_key_preview": openai_key[:10] + "..." if openai_key else None,
                "current_dir": current_dir,
                "project_root": project_root,
                "agent_path": agent_path,
                "agent_path_exists": os.path.exists(agent_path),
                "file_status": file_status,
                "report_workflow_initialized": task_manager.report_workflow is not None,
                "reinit_success": reinit_success
            }
        })
        
    except Exception as e:
        logger.error(f"调试检查失败: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e),
            "traceback": traceback.format_exc()
        }), 500

# 错误处理
@api_bp.errorhandler(404)
def not_found(error):
    return jsonify({"error": "API端点未找到"}), 404

@api_bp.errorhandler(500)
def internal_error(error):
    return jsonify({"error": "服务器内部错误"}), 500 